/*
 * @lc app=leetcode.cn id=1022 lang=typescript
 *
 * [1022] 从根到叶的二进制数之和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function dfs(root: TreeNode | null, val: number): number {
  if (root === null) return 0;
  val = (val << 1) | root.val;
  if (!root.left && !root.right) {
    return val;
  }

  let sum = 0;
  sum = dfs(root.left, val) + dfs(root.right, val);
  return sum;
}

function sumRootToLeaf(root: TreeNode | null): number {
  return dfs(root, 0);
}
// @lc code=end
